package initialize

import (
	"embed"
	"fmt"
	"github.com/AlecAivazis/survey/v2"
	errors2 "github.com/pkg/errors"
	"github.com/urfave/cli/v2"
	"hpmGo/constants"
	"hpmGo/core"
	"hpmGo/utils"
	"os"
	"path/filepath"
)

//go:embed assets
var assets embed.FS

func Action(c *cli.Context) error {
	tem := c.String("template")
	dest, err := os.Getwd()
	if err != nil {
		return errors2.WithMessage(err, "HpmGo init: get cwd failed")
	}
	if tem != "" {
		temDir := fmt.Sprintf("assets/%s.tgz", tem)
		f, err := assets.Open(temDir)
		if err != nil {
			return errors2.WithMessage(err, "HpmGo init: open tar failed")
		}
		defer func() {
			err := f.Close()
			if err != nil {
				panic(err)
			}
		}()
		err = utils.Extract(f, dest)
		if err != nil {
			return err
		}
	} else {
		bundle := core.Bundle{
			BundlePath: filepath.Join(dest),
		}
		err := survey.Ask(constants.INIT_QUESTIONS, &bundle.Manifest)
		if err != nil {
			return errors2.WithMessage(err, "HpmGo init: survey failed")
		}
		err = bundle.SaveManifestToJson()
		if err != nil {
			return err
		}
	}
	fmt.Println("you project has been init in ", dest)
	return nil
}
